package com.wujilee.wujileenetty.netty.netty.decoder;

import io.netty.bootstrap.Bootstrap;
import io.netty.buffer.ByteBuf;
import io.netty.buffer.Unpooled;
import io.netty.channel.ChannelFuture;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelInboundHandlerAdapter;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.nio.NioSocketChannel;
import io.netty.handler.codec.DelimiterBasedFrameDecoder;
import io.netty.handler.codec.LineBasedFrameDecoder;
import io.netty.handler.codec.string.StringDecoder;

import java.io.UnsupportedEncodingException;
import java.util.concurrent.atomic.AtomicInteger;

/**
 * @author liwuji
 * @date 2024/8/27
 * @desc
 **/
public class EchoClient {
    public static void main(String[] args) throws InterruptedException {
        NioEventLoopGroup eventExecutors = new NioEventLoopGroup();
        Bootstrap bootstrap = new Bootstrap();
        bootstrap.group(eventExecutors);
        bootstrap.channel(NioSocketChannel.class);
        bootstrap.handler(new ChannelInitializer<NioSocketChannel>() {
            @Override
            protected void initChannel(NioSocketChannel ch) throws UnsupportedEncodingException {
                // 结束标识
                ByteBuf delimiter = Unpooled.copiedBuffer("$_".getBytes("UTF-8"));
                ch.pipeline().addLast(new DelimiterBasedFrameDecoder(1024, delimiter));
//
                ch.pipeline().addLast(new StringDecoder());
                ch.pipeline().addLast(new ChannelInboundHandlerAdapter() {
                     // 有个问题 消息虽然成功 推送 但是会抛出异常
                    @Override
                    public void channelActive(ChannelHandlerContext ctx) throws Exception {
                        System.out.println("连接建立成功");
                        String msg = " hello wujie  welcome to netty $_";
                        for (int i = 0; i < 10000; i++) {
                            ByteBuf byteBuf = Unpooled.copiedBuffer(msg.getBytes("UTF-8"));
                            ctx.writeAndFlush(byteBuf);
//                            Thread.sleep(1L);
                        }
                    }

                    @Override
                    public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
                        String s = (String) msg;
                        System.out.println("接收到来自服务端的消息: " + s);
                    }

                    @Override
                    public void channelReadComplete(ChannelHandlerContext ctx) throws Exception {
                        ctx.flush();
                    }
                });

            }
        });
        ChannelFuture sync = bootstrap.connect("127.0.0.1", 8080).sync();
        ChannelFuture sync1 = sync.channel().closeFuture().sync();
        eventExecutors.shutdownGracefully();

    }
}
